package cn.wangqi.personal.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Created by admin on 2017/5/22.
 */
public class PropertiesUtil extends PropertyPlaceholderConfigurer {
     Logger logger = Logger.getLogger("PropertiesUtil.class");

     private static Map<String ,String> propertiesMap;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        if(propertiesMap != null){
            logger.warning("properties map will be override!");
        }
        propertiesMap = new HashMap<String, String>();
        Iterator it = props.keySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            propertiesMap.put(keyStr, value);
        }
    }

    public static String getString(String name) {
        if(propertiesMap == null) {
            propertiesMap = new HashMap();
        }
        return (String)propertiesMap.get(name);
    }

    public static String getStringDefault(String name ,String defaultValue) {
        String value = getString(name);
        if (value == null){
            return defaultValue;
        }else{
            return value;
        }
    }

    public void setString(String key, String value) {
        if(propertiesMap == null) {
            propertiesMap = new HashMap();
        }
        propertiesMap.put(key,value);
    }

}
